import React from 'react';
import { Form, Input, Modal, TreeSelect, message, Drawer,Button } from 'antd';
import styles from '../answerLibrary.css';
import Editor from '@/utils/Editor';
import { getAnswerTree, postAddAnswer, postEditAnswer, getInfoAnswer } from '@/services/knowledgemanagement';
import AnswerUtils from '@/utils/answerUtils/answerUtils';
import jsonDataUtils from '@/utils/jsonDataUtils';

class AddOrEditAnswer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      treeData: [],
      row: {}
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  initModal = async (modalType, row, currentNode) => {
    let data = {};
    this.getTreeList();
    if (row !== undefined) {
      const res = await getInfoAnswer({ id: row.id });
      // console.log(res);
      data = res;
    };
    // console.log(modalType);
    this.setState({ visible: true, row: data, }, () => {
      if (modalType === 'edit') {
        this.props.form.setFieldsValue({ question: data.question, categoryId: data.categoryId })
        //处理答案字段
        let answerObj = {
          isDefault: true,
          content: data.answer,
          id: data.id,
          slotValues: [],
          userTagIdList: [],
          contentType: data.contentType + '',    //答案内容类型 0=纯文本类型, 1=富文本类型, 2=跳转卡片 默认为0
        }
        if(jsonDataUtils.isJsonString(data.answer)){
          answerObj.cardVo = JSON.parse(data.answer)
        }
        setTimeout(() => {
          this.AnswerUtils.setAnswers(answerObj)
        },300)
      } else {
        this.props.form.setFieldsValue({ categoryId: currentNode.id })
      }
    })
  }

  /**
   * 获取分类
   */
  getTreeList = async () => {
    const res = await getAnswerTree();
    this.setState({ treeData: res ? res : [] });
  }

  /**
   * 加载树节点
   */
  renderTreeNode = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeSelect.TreeNode value={item.id} title={item.name} key={item.id} disabled={item.parentId === '0'} >
            {this.renderTreeNode(item.children)}
          </TreeSelect.TreeNode>
        )
      } else {
        return <TreeSelect.TreeNode value={item.id} title={item.name} key={item.id} disabled={item.parentId === '0'} />
      }
    })
  }

  /**
   * 关闭弹窗
   */
  cancelModal = () => {
    this.setState({ visible: false })
  }

  /**
   * 确定
   */
  doSubmit = async () => {
    const { row } = this.state;
    const values = await this.props.form.validateFields(['question','categoryId'])
    
    const answerResult = await this.AnswerUtils.getAnswerResult();
    if(answerResult.flag){
      let answer = answerResult.result.content;
      let contentType = answerResult.result.contentType;

      let otherParams = {
        categoryId:values.categoryId,
        question:values.question,
      }
      if (row.id !== undefined && row.id !== null) {
        this.editAnswer({ id: row.id, answer, ...otherParams,contentType });
      } else {
        this.addAnswer({ answer, ...otherParams,contentType });
      }
    }else{
      if(answerResult.message){
        message.error(answerResult.message)
      }
      return false
    }
  };
  /**
   * 新增
   */
  addAnswer = async (data) => {
    const res = await postAddAnswer(data);
    // console.log(res);
    if (res.data) {
      message.success('操作成功')
      this.cancelModal();
      this.props.getList();
    }
  };
  /**
   * 修改
   */
  editAnswer = async (data) => {
    const res = await postEditAnswer(data);
    // console.log(res);
    if (res.data) {
      message.success('操作成功')
      this.cancelModal();
      this.props.getList();
    }
  };

  render() {
    const { visible, treeData } = this.state;
    const { modalType } = this.props;
    const { getFieldDecorator,getFieldValue } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    const formItemForEdit = {
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20, offset: 3 },
      },
    };
    return (
      <Drawer
        title={modalType === 'add' ? '新增答案' : '编辑答案'}
        visible={visible}
        width={800}
        destroyOnClose
        headerStyle={{background:"#F7F9FD",borderBottom:0}}
        className="modelZdy"
        onClose={this.cancelModal}
      >
        <Form {...formItemLayout}>
          <h4 className={styles.htitle}>问题</h4>
          <Form.Item label={'答案标题'}>
            {
              getFieldDecorator('question', {
                rules: [{ required: true, message: '答案标题必填' }]
              })(
                <Input maxLength={100} />
              )
            }
          </Form.Item>
          <h4 className={styles.htitle}>答案内容</h4>
          <Form.Item {...formItemForEdit} className={styles.editForm}>
            <div>
              <AnswerUtils getFieldDecorator={getFieldDecorator} form={this.props.form} getFieldValue={getFieldValue} onRef={ref => this.AnswerUtils = ref} />
            </div>
          </Form.Item>
          <h4 className={styles.htitle}>知识点相关</h4>
          <Form.Item label={'选择分类'}>
            {
              getFieldDecorator('categoryId')(
                <TreeSelect allowClear={false}>
                  {this.renderTreeNode(treeData)}
                </TreeSelect>
              )
            }
          </Form.Item>
        </Form>

        <div
            style={{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button onClick={this.cancelModal} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={this.doSubmit} type="primary">
              确定
            </Button>
          </div>
      </Drawer>
    );
  }
}
export default Form.create()(AddOrEditAnswer)
